<template>
  <div class="dashboard-container">
    <el-row :gutter="20" v-loading="loading">
      <!-- 统计卡片 -->
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6" class="card-panel-col">
        <el-card class="box-card stat-card" shadow="hover">
          <div class="card-header">
            <i class="el-icon-user"></i>
            <span>用户总数</span>
          </div>
          <div class="card-body">
            <div class="card-value">{{ formatNumber(dashboardStats.userCount) }}</div>
            <div class="card-footer">
              <span>较上周</span>
              <el-tag size="mini" :type="getChangeType(dashboardStats.userCountChange)">
                {{ formatPercent(dashboardStats.userCountChange) }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6" class="card-panel-col">
        <el-card class="box-card stat-card" shadow="hover">
          <div class="card-header">
            <i class="el-icon-user-solid"></i>
            <span>角色总数</span>
          </div>
          <div class="card-body">
            <div class="card-value">{{ dashboardStats.roleCount }}</div>
            <div class="card-footer">
              <span>较上周</span>
              <el-tag size="mini" :type="getChangeType(dashboardStats.roleCountChange)">
                {{ formatPercent(dashboardStats.roleCountChange) }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6" class="card-panel-col">
        <el-card class="box-card stat-card" shadow="hover">
          <div class="card-header">
            <i class="el-icon-menu"></i>
            <span>菜单总数</span>
          </div>
          <div class="card-body">
            <div class="card-value">{{ dashboardStats.menuCount }}</div>
            <div class="card-footer">
              <span>较上周</span>
              <el-tag size="mini" :type="getChangeType(dashboardStats.menuCountChange)">
                {{ formatPercent(dashboardStats.menuCountChange) }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6" class="card-panel-col">
        <el-card class="box-card stat-card" shadow="hover">
          <div class="card-header">
            <i class="el-icon-s-operation"></i>
            <span>系统访问</span>
          </div>
          <div class="card-body">
            <div class="card-value">{{ formatNumber(dashboardStats.systemVisits) }}</div>
            <div class="card-footer">
              <span>较上周</span>
              <el-tag size="mini" :type="getChangeType(dashboardStats.systemVisitsChange)">
                {{ formatPercent(dashboardStats.systemVisitsChange) }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="panel-group">
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card shadow="hover" class="login-records-card">
          <template #header>
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span>最近登录记录</span>
              <el-button type="text" icon="el-icon-refresh" @click="refreshData">刷新</el-button>
            </div>
          </template>
          <el-table :data="loginLogs" style="width: 100%" stripe class="login-records-table">
            <el-table-column prop="username" label="用户名" min-width="80"></el-table-column>
            <el-table-column prop="ip" label="登录IP" min-width="80"></el-table-column>
            <el-table-column prop="time" label="登录时间" min-width="120"></el-table-column>
            <el-table-column prop="status" label="状态" min-width="60" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.status === '成功' ? 'success' : 'danger'">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card shadow="hover" class="system-info-card">
          <template #header>
            <span>系统信息</span>
          </template>
          <el-descriptions :column="1" border class="system-info">
            <el-descriptions-item label="系统版本">v1.0.0</el-descriptions-item>
            <el-descriptions-item label="最后更新时间">2024-07-16 12:00:00</el-descriptions-item>
          </el-descriptions>
        </el-card>
        
        <!-- 主题设置卡片 -->
        <el-card shadow="hover" class="theme-settings-card">
          <template #header>
            <div class="theme-header">
              <span>主题设置</span>
            </div>
          </template>
          <div class="theme-settings">
            <div class="setting-item">
              <span class="setting-label">选择主题：</span>
              <div class="theme-grid">
                <div 
                  v-for="theme in availableThemes" 
                  :key="theme.name" 
                  class="theme-item"
                  :class="{'active': currentTheme === theme.name}"
                  @click="handleThemeChange(theme.name)"
                >
                  <div class="theme-icon-box" :class="`theme-${theme.name}`">
                    <i :class="theme.icon"></i>
                  </div>
                  <span class="theme-name">{{ theme.label }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getDashboardStatsMock, getRecentLoginsMock } from '@/api/dashboard'


export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters([
      'currentTheme',
      'availableThemes'
    ])
  },
  data() {
    return {
      loading: false,
      dashboardStats: {
        userCount: 0,
        userCountChange: 0,
        roleCount: 0,
        roleCountChange: 0,
        menuCount: 0,
        menuCountChange: 0,
        systemVisits: 0,
        systemVisitsChange: 0
      },
      loginLogs: []
    }
  },
  created() {
    this.loadDashboardData()
  },
  methods: {
    // 加载Dashboard数据
    async loadDashboardData() {
      this.loading = true
      
      try {
        // 并行加载统计数据和登录日志
        const [statsResponse, logsResponse] = await Promise.all([
          getDashboardStatsMock(),
          getRecentLoginsMock()
        ])
        
        if (statsResponse.code === 200) {
          this.dashboardStats = statsResponse.data
        }
        
        if (logsResponse.code === 200) {
          this.loginLogs = logsResponse.data
        }
        
        this.$messageBox.success('数据加载完成')
      } catch (error) {
        console.error('加载Dashboard数据失败:', error)
        this.$messageBox.error('数据加载失败，请刷新重试')
      } finally {
        this.loading = false
      }
    },
    
    // 格式化数字（添加千位分隔符）
    formatNumber(num) {
      if (num === undefined || num === null) return '0'
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },
    
    // 格式化百分比
    formatPercent(percent) {
      if (percent === undefined || percent === null) return '0.0%'
      const sign = percent >= 0 ? '+' : ''
      return `${sign}${percent.toFixed(1)}%`
    },
    
    // 获取变化类型（用于标签颜色）
    getChangeType(percent) {
      if (percent > 0) return 'success'
      if (percent < 0) return 'warning'
      return 'info'
    },
    
    // 刷新数据
    refreshData() {
      this.loadDashboardData()
    },
    
    themeIcon(themeName) {
      return themeName === 'dark' ? 'el-icon-moon' : 'el-icon-sunny'
    },
    
    handleThemeChange(theme) {
      this.$store.dispatch('theme/changeTheme', theme)
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  margin: 0;
  width: 100%;
  box-sizing: border-box;
  min-height: 100%;
  
  .card-panel-col {
    margin-bottom: 20px;
  }
  
  .box-card {
    height: 100%;
    
    .card-header {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      
      i {
        font-size: 20px;
        margin-right: 10px;
        color: #409EFF;
      }
      
      span {
        font-size: 16px;
        font-weight: bold;
      }
    }
    
    .card-body {
      .card-value {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 15px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      
      .card-footer {
        display: flex;
        align-items: center;
        
        span {
          margin-right: 10px;
          color: #909399;
        }
      }
    }
  }
  
  .panel-group {
    margin-top: 20px;
    
    .el-card {
      margin-bottom: 20px;
    }
  }

  .theme-settings-card {
    margin-top: 20px;
    
    .theme-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    
    .theme-settings {
      .setting-item {
        display: flex;
        flex-direction: column;
        margin-bottom: 15px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .setting-label {
          font-weight: bold;
          margin-right: 10px;
          margin-bottom: 10px;
        }
        
        .theme-grid {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 12px;
          margin-bottom: 15px;
          
          .theme-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            cursor: pointer;
            transition: transform 0.2s ease;
            
            &:hover {
              transform: translateY(-2px);
            }
            
            &.active .theme-icon-box {
              border: 2px solid #409EFF;
              transform: scale(1.05);
            }
            
            .theme-icon-box {
              width: 50px;
              height: 50px;
              border-radius: 8px;
              display: flex;
              align-items: center;
              justify-content: center;
              margin-bottom: 5px;
              transition: all 0.2s ease;
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
              
              i {
                font-size: 24px;
              }
              
              &.theme-light {
                background-color: #ffffff;
                color: #303133;
              }
              
              &.theme-dark {
                background-color: #121212;
                color: #e5eaf3;
              }
              

            }
            
            .theme-name {
              font-size: 12px;
              margin-top: 4px;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 1024px) {
  .dashboard-container {
    padding: 10px;
  }
}
</style> 